package com.example.pda.net;


import com.example.pda.common.Utils;
import com.example.pda.data.Result;

import java.io.IOException;
import java.lang.ref.WeakReference;

import androidx.annotation.NonNull;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public abstract class ICallback<T> implements Callback<CallResult<T>> {

    @Override
    public void onResponse(@NonNull Call<CallResult<T>> call, @NonNull Response<CallResult<T>> response) {
        Utils.LogI( "-->http is onNext");
        ApiException apiException = null;
        if (response.isSuccessful()) {
            CallResult<T> body = response.body();
            if (body != null) {
                String msg = body.getMsg();
                if (body.isSuccess()) {
                    onSuccess(body.getData());
                } else {
                    onError(new ApiException(new Throwable(msg), ApiException.REQUEST_FAILURE));
                }
            } else {
                apiException = new ApiException(new Throwable("Response is null."), ApiException.UNKNOWN);
            }
        } else {
            try {
                assert response.errorBody() != null;
                String string = response.errorBody().string();
                apiException = new ApiException(new Throwable(string), response.code());
            } catch (IOException e) {
                apiException = new ApiException(new Throwable(e.getMessage()), response.code());
            }
        }
        if (apiException != null) {
            onFailure(apiException);
        }
    }

    @Override
    public void onFailure(@NonNull Call<CallResult<T>> call, @NonNull Throwable t) {
        ApiException ex = ApiException.handleException(t);
        onFailure(ex);
    }

    public void onFailure(ApiException e) {
        Utils.LogI("ApiException err:" + e);
    }

    public abstract void onSuccess(T o);

    protected void onError(ApiException e) {
        Utils.LogI("--> onError");
    }

}
